(function($, doc) {
	var MIN_SOUND_TIME = 800;
	var userinfo = app.getState();
	var uid = userinfo.user_id;
	//阻尼系数
	var deceleration = mui.os.ios ? 0.003 : 0.0009;
	var ws;
	/*var header = app.myurl('chatHeader') || plus.webview.currentWebview().chatHeader;
	var chatName = app.myurl('chatTitle') || plus.webview.currentWebview().chatTitle;
	var roomType = app.myurl('roomType') || plus.webview.currentWebview().roomType;
	roomId = app.myurl('roomId') || plus.webview.currentWebview().roomId;*/

	$.init({
		swipeBack: true,
		gestureConfig: {
			tap: true, //默认为true
			doubletap: true, //默认为false
			longtap: true, //默认为false
			swipe: true, //默认为true
			drag: true, //默认为true
			hold: true, //默认为false，不监听
			release: true //默认为false，不监听
		},
		beforeback: function() {
			//关闭时候的一些操作
			//socket.onclose();
			//获得列表界面的webview  
			var list = plus.webview.currentWebview().opener();
			//触发列表界面的自定义事件（refresh）,从而进行数据刷新  
			mui.fire(list, 'refreshList');
			//返回true，继续页面关闭逻辑  
			return true;
		}
	});

	template.config('escape', false);

	//$.plusReady=function(fn){fn();};
	$.plusReady(function() {
		var header = plus.webview.currentWebview().chatHeader;
		var chatName = plus.webview.currentWebview().chatTitle;
		var roomType = plus.webview.currentWebview().roomType;
		var roomId = plus.webview.currentWebview().roomId;
		if(!roomId) {
			mui.alert('error!');
		}
		//console.log(roomType);
		/*
		
		if(maindata && maindata.length > 0) {
			var allnum = 0;
			for(var i = 0; i < maindata.length; i++) {

				if(maindata[i]['f_id'] == roomId) {
					maindata[i]['msgnum'] = 0;
				} else {
					allnum = maindata[i]['msgnum'] + allnum;
				}
			}
			localStorage.setItem('chatnum' + uid, allnum);
			localStorage.setItem('mainlist' + uid, JSON.stringify(maindata));
		}*/
		var venderToIndex = function(msg, type, uptime) {
			var maindata = JSON.parse(localStorage.getItem('mainlist' + uid) || '[]');
			
			var allnum = 0;
			var uptime = uptime || 1;
			var has = false;
			var showmsg = app.parseMainMsg(msg, type);
			var now = Date.parse(new Date()) / 1000;
			for(var i = 0; i < maindata.length; i++) {
				if(maindata[i]['f_id'] == roomId) {
					maindata[i]['msgnum'] = 0;
					if(uptime > 0) {
						maindata[i]['add_time'] = now;
					}
					
					maindata[i]['msg'] = showmsg;
					has = true;
					//maindata[i]['show_time'] = app.dateStr(maindata[i]['add_time']);
				}
				allnum = allnum + maindata[i]['msgnum'];
			}
			if(has === false) {
				var add = {
					'f_id' : roomId,
					'f_name' : chatName,
					'ctype' : roomType,
					'f_header' : header,
					'msgnum' : 0,
					'add_time' : now,
					'msg' : showmsg
				};
				maindata.push(add);
			}
			localStorage.setItem('chatnum' + uid, allnum);
			localStorage.setItem('mainlist' + uid, JSON.stringify(maindata));
		};

		// 连接服务端
		function connect() {
			// 创建websocket
			ws = new WebSocket(chaturl);
			// 当socket连接打开时，输入用户名
			ws.onopen = onopen;
			// 当有消息时根据消息类型显示不同信息
			ws.onmessage = onmessage;
			ws.onclose = function() {
				console.log("连接关闭，定时重连");
				connect();
			};
			ws.onerror = function() {
				console.log("出现错误");
			};
		}

		// 连接建立时发送登录信息
		function onopen() {
			userinfo.type = 'login';
			userinfo.roomId = roomId;
			userinfo.ctype = roomType;
			// 登录
			ws.send(JSON.stringify(userinfo));
			console.log("聊天页面websocket握手成功!");
		}

		//}
		if(header == './static/images/1.png') {
			header = '../../static/images/1.png';
		}
		document.querySelector('.mui-title').innerHTML = chatName;

		plus.webview.currentWebview().setStyle({
			softinputMode: "adjustResize"
		});
		var showKeyboard = function() {
			if($.os.ios) {
				var webView = plus.webview.currentWebview().nativeInstanceObject();
				webView.plusCallMethod({
					"setKeyboardDisplayRequiresUserAction": false
				});
			} else {
				var Context = plus.android.importClass("android.content.Context");
				var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
				var main = plus.android.runtimeMainActivity();
				var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
				//var view = ((ViewGroup)main.findViewById(android.R.id.content)).getChildAt(0);
				imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);
				//alert("ll");
			}
		};

		var record = [];
		var myid = [];
		//app.clearReadNum(uid, roomId);
		var ui = {
			body: doc.querySelector('body'),
			footer: doc.querySelector('footer'),
			footerRight: doc.querySelector('.footer-left'),
			footerLeft: doc.querySelector('.footer-right'),
			btnMsgImage: doc.querySelector('#msg-type'),
			boxMsgText: doc.querySelector('#msg-text'),
			boxMsgSound: doc.querySelector('#msg-sound'),
			btnMsgType: doc.querySelector('#msg-image'),
			areaMsgList: doc.querySelector('#msg-list'),
			boxSoundAlert: doc.querySelector('#sound-alert'),
			h: doc.querySelector('#h'),
			content: doc.querySelector('.mui-content')
		};
		ui.h.style.width = ui.boxMsgText.offsetWidth + 'px';
		//alert(ui.boxMsgText.offsetWidth );
		var footerPadding = ui.footer.offsetHeight - ui.boxMsgText.offsetHeight;
		var msgItemTap = function(msgItem, event) {
			var msgType = msgItem.getAttribute('msg-type');
			var msgContent = msgItem.getAttribute('msg-content')
			if(msgType == 'sound') {
				player = plus.audio.createPlayer(msgContent);
				var playState = msgItem.querySelector('.play-state');
				playState.innerText = '正在播放...';
				player.play(function() {
					playState.innerText = '点击播放';
				}, function(e) {
					playState.innerText = '点击播放';
				});
			}
		};
		var imageViewer = new $.ImageViewer('.msg-content-image', {
			dbl: false
		});
		var bindMsgList = function() {
			//定义传递给模板的变量
			ui.areaMsgList.innerHTML = template('msg-template', {
				"record": record,
				"header": header
			});
			var msgItems = ui.areaMsgList.querySelectorAll('.msg-item');
			[].forEach.call(msgItems, function(item, index) {
				item.addEventListener('tap', function(event) {
					msgItemTap(item, event);
				}, false);
			});
			imageViewer.findAllImage();
			ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
			//renderMsgList();
		};
		var page = 1;

		function getServiceData() {
			var geturl = apiurl + 'chat/getlist?user_id=' + uid + '&fid=' + roomId + '&ctype=' + roomType + '&page=' + page;
		    //console.log(geturl);
			$.get(geturl, function(res) {
				//console.log(JSON.stringify(res));
				if(res.status > 0) {
					var list = res.list;
					if(list && list.length > 0) {
						page++;
						//var adddata = {};
						for(var p in list) {
							var val = list[p];
							//console.log(val['f_type']);
							if(val['f_id'] == uid) {
								val['f_id'] = 'self';
							}
							var pashdata = {
								sender: val['f_id'],
								type: val['r_type'],
								content: val['t_msg']
							};
							record.push(pashdata);

						}
						if(pashdata) {
							venderToIndex(pashdata.content, pashdata.type, 0);
						}
						bindMsgList();
						//localStorage.setItem('chatdetail' + userkey, JSON.stringify(record));
					}
				}
			});
		}
		getServiceData();
		/*
		doc.addEventListener("swipeup",function(){
			getServiceData();
		});*/
		//点击红包
		document.getElementById("red_packet").addEventListener('tap', function() {
			mui.openWindow({
				url: '../../pages/chat/red_packet.html',
				id: 'pages/chat/red_packet',
				extras: {
					roomId: roomId
				}
			});
		});

		//点击转账 
		document.getElementById("transfer_accounts").addEventListener('tap', function() {
			/*mui.openWindow({
				url: '../../pages/chat/transfer_accounts.html',
				id: 'pages/chat/transfer_accounts',
				extras: {
					roomId: roomId
				}
			}); */

			var postUrl = apiurl + "wallet/getWallets";
			var postdata = {
				from_id: uid,
				to_id: uid
			};

			$.post(postUrl, postdata, function(res) {
				if(res.status == 1) {
					var f = res.data.from;
					var t = res.data.to;
					var url = "../../pages/wallet/sendTxEmb.html?id=" + f.id + "&name=" + f.name + "&pubkey=" + f.pubkey + "&type=" + f.type + "&tokens=" + f.tokens + "&isdefault=1&user_id=" + uid + "&to=" + t.address;
					mui.openWindow({
						url: url,
						id: 'pages/chat/transfer_accounts',
						extras: {
							roomId: roomId
						}
					});
				} else {
					mui.alert(res.msg);
				}
			});
		});
		
		window.addEventListener('resize', function() {
			ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;

		}, false);

		//$('#msg-list').pullToRefresh.pullDownLoading();
		var sendMsg = function(msg) {
			record.push(msg);
			venderToIndex(msg.content, msg.type, 1);
			bindMsgList();
			toRobot(msg);
		};

		var toRobot = function(info) {
			var toUrl = apiurl + 'chat/addinfo';
			var msgInfo = {
				type: 'say',
				user_id: uid,
				user_name: userinfo.name,
				user_header: userinfo.avatar ? userinfo.avatar : '',
				room_id: roomId,
				chat_name: chatName,
				header: header,
				msg: info.content,
				ftype: info.type,
				ctype: roomType
			};
			//console.log(roomType);
			ws.send(JSON.stringify(msgInfo));

		};
		// 服务端发来消息时
		function onmessage(e) {
			console.log(e.data);
			var data = eval("(" + e.data + ")");
			var rtinfo = data.rtinfo;
			//var data = JSON.parse(e.data);
			switch(data['type']) {
				// 服务端ping客户端
				case 'ping':
					break;
					// 登录 更新用户列表
				case 'login':

					break;
					// 发言
				case 'say':
					if(rtinfo['f_id'] != uid) {
						var emsg = {
							sender: rtinfo['f_id'],
							type: rtinfo['r_type'],
							content: rtinfo['t_msg']
						};
						record.push(emsg);
						//saveMsg(record);
						venderToIndex(rtinfo['t_msg'],rtinfo['r_type'], 1);
						bindMsgList();
					}

					//sendMsg(emsg);
					break;
					// 用户退出 更新用户列表
				case 'logout':
					break;

			}
		}
		doc.querySelector('#biaoqingbao').innerHTML = template('face-templete', {});
		//选择表情
		mui('#selectFace').on('tap', 'img', function() {
			if(ui.boxMsgText.innerHTML != '') {
				document.querySelector('.mui-icon-paperplane').style.display = 'block';
				document.querySelector('.mui-icon-plus').style.display = 'none';
			} else {
				document.querySelector('.mui-icon-paperplane').style.display = 'none';
				document.querySelector('.mui-icon-plus').style.display = 'block';
			}
			var faceImg = this.getAttribute('src');
			ui.boxMsgText.innerHTML += '<img src="' + faceImg + '" />';
			//(function(){ui.boxMsgText.focus();},100);
			/*
			sendMsg({
				id: record.length,
				sender: 'self',
				type: 'image',
				content: faceImg
			});*/
		});
		mui("#biaoqingbao").slider({
			interval: 0
		});

		//mui('#selectFace').slider();
		//					
		function msgTextFocus() {
			ui.boxMsgText.focus();
			setTimeout(function() {
				ui.boxMsgText.focus();
			}, 150);
		}
		//解决长按“发送”按钮，导致键盘关闭的问题；
		ui.footerLeft.addEventListener('touchstart', function(event) {
			if(ui.btnMsgImage.classList.contains('mui-icon-paperplane')) {
				msgTextFocus();
				event.preventDefault();
			}
		});
		//解决长按“发送”按钮，导致键盘关闭的问题；
		ui.footerLeft.addEventListener('touchmove', function(event) {
			if(ui.btnMsgImage.classList.contains('mui-icon-paperplane')) {
				msgTextFocus();
				event.preventDefault();
			}
		});
		//发送文字
		document.querySelector('.mui-icon-paperplane').addEventListener('click', function() {
			//							showKeyboard();
			ui.boxMsgText.focus();
			setTimeout(function() {
				ui.boxMsgText.focus();
				document.querySelector('#Gallery').style.display = 'none';
				document.querySelector('#biaoqingbao').style.display = 'none';
				document.querySelector('footer').style.bottom = '0px';
			}, 150);
			//							event.detail.gesture.preventDefault();
			sendMsg({
				sender: 'self',
				type: 'text',
				content: ui.boxMsgText.innerHTML.replace(new RegExp('\n', 'gm'), '<br/>')
			});
			ui.boxMsgText.innerHTML = '';
			$.trigger(ui.boxMsgText, 'input', null);
		});
		//显示按住说话框
		ui.footerRight.addEventListener('release', function(event) {
			if(ui.btnMsgType.classList.contains('yuyin')) {
				ui.btnMsgType.classList.add('jianpan');
				ui.btnMsgType.classList.remove('yuyin');
				ui.boxMsgText.style.display = 'none';
				ui.boxMsgSound.style.display = 'block';

				document.querySelector('#biaoqing').classList.add('icon-biaoqing');
				document.querySelector('#biaoqing').classList.remove('jianpan');
				document.querySelector('#biaoqingbao').style.display = 'none';
				document.querySelector('#Gallery').style.display = 'none';
				document.querySelector('footer').style.bottom = '0px';

				document.body.focus();
				ui.boxMsgText.blur();
			} else if(ui.btnMsgType.classList.contains('jianpan')) {
				ui.btnMsgType.classList.add('yuyin');
				ui.btnMsgType.classList.remove('jianpan');
				ui.boxMsgSound.style.display = 'none';
				ui.boxMsgText.style.display = 'block';

				document.querySelector('#biaoqingbao').style.display = 'none';
				document.querySelector('#Gallery').style.display = 'none';
				document.querySelector('footer').style.bottom = '0px';
				//--
				//showKeyboard();
				ui.boxMsgText.focus();
				setTimeout(function() {
					ui.boxMsgText.focus();
				}, 150);
			}
		}, false);

		//相机功能 takePhoto
		document.querySelector('.takePhoto').addEventListener('tap', function(event) {
			var btnArray = [{
				title: "拍照"
			}, {
				title: "从相册选择"
			}];
			var uploadImg = function(path) {
				var img = new Image();
				img.src = path;
				img.onload = function() {
					var that = this;
					//生成比例 
					var w = that.width,
						h = that.height,
						scale = w / h;
					w = 480 || w; //480  你想压缩到多大
					h = w / scale;

					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					canvas.setAttribute('width', w);
					canvas.setAttribute('height', h);
					ctx.drawImage(that, 0, 0, w, h);
					var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
					//files.push({name:"file"+index,pic:base64});   // 把base64数据丢进数组，上传要用。
					//index++;   	
					//var pic = document.getElementById("x");    
					//pic.src = base64; //这里丢到img 的 src 里面就能看到效果了
					console.log(base64);
					base64 = base64.replace('data:image/jpeg;base64,', '');
					$.post(apiurl + 'index/upload', {
						file: base64,
						type: 'img'
					}, function(res) {
						console.log(res.status);
						if(res.status > 0) {
							sendMsg({
								id: record.length,
								sender: 'self',
								type: 'image',
								content: serverurl + res.url
							});
						} else {
							sendMsg({
								id: record.length,
								sender: 'self',
								type: 'image',
								content: base64
							});
						}
					});

				}
			};
			plus.nativeUI.actionSheet({
				title: "选择照片",
				cancel: "取消",
				buttons: btnArray
			}, function(e) {
				var index = e.index;
				switch(index) {
					case 0:
						break;
					case 1:
						var cmr = plus.camera.getCamera();
						cmr.captureImage(function(path) {
							uploadImg("file://" + plus.io.convertLocalFileSystemURL(path));
						}, function(err) {});
						break;
					case 2:
						//多选图片
						plus.gallery.pick(function(e) {
							for(var i in e.files) {
								uploadImg(e.files[i]);
							}
						}, function(e) {}, {
							filter: "image",
							multiple: true
						});
						break;
				}
			});
		}, false);

		var setSoundAlertVisable = function(show) {
			if(show) {
				ui.boxSoundAlert.style.display = 'block';
				ui.boxSoundAlert.style.opacity = 1;
			} else {
				ui.boxSoundAlert.style.opacity = 0;
				//fadeOut 完成再真正隐藏
				setTimeout(function() {
					ui.boxSoundAlert.style.display = 'none';
				}, 200);
			}
		};
		var recordCancel = false;
		var recorder = null;
		var audio_tips = document.getElementById("audio_tips");
		var startTimestamp = null;
		var stopTimestamp = null;
		var stopTimer = null;

		//录音语音文件转base64字符串
		function Audio2dataURL(path) {
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				entry.file(function(file) {
					var reader = new plus.io.FileReader();
					reader.onloadend = function(e) {
						var base64 = e.target.result.replace('data:audio/amr;base64,', '');
						console.log(base64);
						$.post(apiurl + 'index/upload', {
							file: base64,
							type: 'sound'
						}, function(res) {
							console.log(res.status);
							if(res.status > 0) {
								sendMsg({
									sender: 'self',
									type: 'sound',
									content: serverurl + res.url
								});
							} else {
								sendMsg({
									sender: 'self',
									type: 'sound',
									content: path
								});
							}
						});
						/*
						send({
							sender: 'self',
							type: 'sound',
							content: path
						});*/

					};
					reader.readAsDataURL(file);
				}, function(e) {
					mui.toast("读写出现异常: " + e.message);
				})
			})
		}
		ui.boxMsgSound.addEventListener('hold', function(event) {
			recordCancel = false;
			if(stopTimer) clearTimeout(stopTimer);
			audio_tips.innerHTML = "手指上划，取消发送";
			ui.boxSoundAlert.classList.remove('rprogress-sigh');
			setSoundAlertVisable(true);
			recorder = plus.audio.getRecorder();
			if(recorder == null) {
				plus.nativeUI.toast("不能获取录音对象");
				return;
			}
			startTimestamp = (new Date()).getTime();
			recorder.record({
				filename: "_doc/audio/"
			}, function(path) {
				if(recordCancel) return;
				//uploadSound(path);
				//Audio2dataURL(path);
				Audio2dataURL(path);

			}, function(e) {
				plus.nativeUI.toast("录音时出现异常: " + e.message);
			});
		}, false);
		ui.body.addEventListener('drag', function(event) {
			//console.log('drag');
			if(Math.abs(event.detail.deltaY) > 50) {
				if(!recordCancel) {
					recordCancel = true;
					if(!audio_tips.classList.contains("cancel")) {
						audio_tips.classList.add("cancel");
					}
					audio_tips.innerHTML = "松开手指，取消发送";
				}
			} else {
				if(recordCancel) {
					recordCancel = false;
					if(audio_tips.classList.contains("cancel")) {
						audio_tips.classList.remove("cancel");
					}
					audio_tips.innerHTML = "手指上划，取消发送";
				}
			}
		}, false);
		ui.boxMsgSound.addEventListener('release', function(event) {
			//console.log('release');
			if(audio_tips.classList.contains("cancel")) {
				audio_tips.classList.remove("cancel");
				audio_tips.innerHTML = "手指上划，取消发送";
			}
			//
			stopTimestamp = (new Date()).getTime();
			if(stopTimestamp - startTimestamp < MIN_SOUND_TIME) {
				audio_tips.innerHTML = "录音时间太短";
				ui.boxSoundAlert.classList.add('rprogress-sigh');
				recordCancel = true;
				stopTimer = setTimeout(function() {
					setSoundAlertVisable(false);
				}, 800);
			} else {
				setSoundAlertVisable(false);
			}
			recorder.stop();
		}, false);
		ui.boxMsgSound.addEventListener("touchstart", function(e) {
			//console.log("start....");
			e.preventDefault();
		});
		//显示发送按钮
		ui.boxMsgText.addEventListener('input', function(event) {
			//						ui.btnMsgImage.classList[ui.boxMsgText.innerHTML == '' ? 'remove' : 'add']('mui-icon-paperplane');
			if(ui.boxMsgText.innerHTML != '') {
				document.querySelector('.mui-icon-paperplane').style.display = 'block';
				document.querySelector('.mui-icon-plus').style.display = 'none';
			} else {
				document.querySelector('.mui-icon-paperplane').style.display = 'none';
				document.querySelector('.mui-icon-plus').style.display = 'block';
			}
			ui.btnMsgImage.setAttribute("for", ui.boxMsgText.value == '' ? '' : 'msg-text');
			ui.h.innerText = ui.boxMsgText.innerHTML.replace(new RegExp('\n', 'gm'), '\n-') || '-';
			ui.footer.style.height = (ui.h.offsetHeight + footerPadding) + 'px';
			ui.content.style.paddingBottom = ui.footer.style.height;
		});

		//显示键盘
		var focus = false;
		ui.boxMsgText.addEventListener('tap', function(event) {
			document.querySelector('#biaoqingbao').style.display = 'none';
			document.querySelector('#Gallery').style.display = 'none';
			document.querySelector('footer').style.bottom = '0px';

			document.querySelector('#biaoqing').classList.add('icon-biaoqing');
			document.querySelector('#biaoqing').classList.remove('jianpan');

			ui.content.style.paddingBottom = '50px';

			ui.boxMsgText.focus();
			setTimeout(function() {
				ui.boxMsgText.focus();
			}, 0);
			focus = true;
			setTimeout(function() {
				focus = false;
			}, 1000);
			event.detail.gesture.preventDefault();
		}, false);
		//点击消息列表，关闭键盘
		ui.areaMsgList.addEventListener('click', function(event) {
			if(!focus) {
				ui.boxMsgText.blur();
			}
			console.log('click');
			document.querySelector('#biaoqingbao').style.display = 'none';
			document.querySelector('#Gallery').style.display = 'none';
			document.querySelector('footer').style.bottom = '0px';

			document.querySelector('#biaoqing').classList.add('icon-biaoqing');
			document.querySelector('#biaoqing').classList.remove('jianpan');

			ui.content.style.paddingBottom = '50px';
		})
		//显示更多
		document.querySelector('.mui-icon-plus').addEventListener('tap', function() {
			if(document.querySelector('#Gallery').style.display == 'none') {
				document.querySelector('footer').style.bottom = '37%';
				//document.querySelector('footer').style.bottom = '120px';
				document.querySelector('#biaoqingbao').style.display = 'none';
				document.querySelector('#Gallery').style.display = 'block';
				ui.boxMsgText.blur();
			} else {
				document.querySelector('footer').style.bottom = '0px';
				document.querySelector('#Gallery').style.display = 'none';
				document.querySelector('#biaoqingbao').style.display = 'none';
				ui.boxMsgText.blur();
			}
		});
		//显示表情
		document.querySelector('#biaoqing').addEventListener('release', function(event) {
			if(this.classList.contains('icon-biaoqing')) {
				this.classList.add('jianpan');
				this.classList.remove('icon-biaoqing');
				document.querySelector('footer').style.bottom = '28%';
				document.querySelector('#biaoqingbao').style.display = 'block';
				document.querySelector('#Gallery').style.display = 'none';

				ui.content.style.paddingBottom = '60%';

				ui.boxMsgText.style.display = 'block';
				ui.boxMsgSound.style.display = 'none';

				ui.btnMsgType.classList.add('yuyin');
				ui.btnMsgType.classList.remove('jianpan');
				document.body.focus();
				ui.boxMsgText.blur();
			} else if(this.classList.contains('jianpan')) {
				this.classList.add('icon-biaoqing');
				this.classList.remove('jianpan');

				ui.boxMsgText.style.display = 'block';
				ui.boxMsgSound.style.display = 'none';

				ui.content.style.paddingBottom = '50px';

				document.querySelector('#biaoqingbao').style.display = 'none';
				document.querySelector('#Gallery').style.display = 'none';
				document.querySelector('footer').style.bottom = '0px';
				//--
				//showKeyboard();
				ui.boxMsgText.focus();
				setTimeout(function() {
					ui.boxMsgText.focus();
				}, 150);
			}
		}, false);
		//显示聊天信息页
		mui('.mui-bar-nav').on('tap', '.icon-wo', function() {
			if(roomType == 1) {
				mui.openWindow({
					url: 'chat_info.html',
					id: 'chat_info.html',
	
					show: {
						autoShow: true,
						aniShow: 'slide-in-right',
						duration: 100
					},
					waiting: {
						autoShow: true,
						title: 'waiting...'
					},
					extras: {
						chatHeader: header,
						chatName: chatName,
						roomId : roomId
					}
				});
			}else{
				mui.openWindow({
					url: 'group_set.html',
					id: 'group_set.html',
	
					show: {
						autoShow: true,
						aniShow: 'slide-in-right',
						duration: 100
					},
					waiting: {
						autoShow: true,
						title: 'waiting...'
					},
					extras: {
						chatHeader: header,
						chatName: chatName,
						roomId : roomId
					}
				});
			}
			
		});
		mui('#msg-list').on('tap', '.msg-user-img', function() {
			var fid = this.getAttribute('fid');
			mui.openWindow({
				url: '/pages/user/other_detail.html',
				id: '/pages/user/other_detail.html',

				show: {
					autoShow: true,
					aniShow: 'slide-in-right',
					duration: 100
				},
				waiting: {
					autoShow: true,
					title: 'waiting...'
				},
				extras: {
					fid: fid
				}
			})
		});
		mui('#msg-list').on('longtap', '.msg-content-inner', function() {
			//console.log('触发长按');
			plus.nativeUI.actionSheet({
				title: "操作",
				cancel: "取消",
				buttons: [{
					title: "复制"
				}, {
					title: "发送给朋友"
				}, {
					title: "撤回"
				}, {
					title: "删除"
				}]
			}, function(e) {
				console.log("User pressed: " + e.index);
				var txt = this.innerText;
				if(e.index == 1) {
					if(mui.os.android) {
						var Context = plus.android.importClass("android.content.Context");
						var main = plus.android.runtimeMainActivity();
						var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
						plus.android.invoke(clip, "setText", txt);
					} else {
						var UIPasteboard = plus.ios.importClass("UIPasteboard");
						var generalPasteboard = UIPasteboard.generalPasteboard();
						generalPasteboard.setValueforPasteboardType(txt, "public.utf8-plain-text");
					}
				}
			});
		});
		// 录像
		function getVideo() {
			var File = plus.android.importClass("java.io.File");
			var Uri = plus.android.importClass("android.net.Uri");
			var MediaStore = plus.android.importClass("android.provider.MediaStore");
			var Intent = plus.android.importClass("android.content.Intent");
			var intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); //0 最低质量, 1高质量MediaStore.EXTRA_SIZE_LIMIT
			//intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
			intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); //控制录制时间单位秒
			var main = plus.android.runtimeMainActivity();
			main.startActivityForResult(intent, 1);
			main.onActivityResult = function(request, code, data) {
				console.log("code" + code + "request" + request);
				if(request == 1001) { //相册Activity返回码

				} else {
					plus.gallery.pick(function(path) {
						//console.log(path); //视频路径
						sendMsg({
							sender: 'self',
							type: 'video',
							content: path
						});

					}, function(e) {
						console.log("取消选择视频");
					}, {
						filter: "video" //筛选类型
					});
				}
			}
		}
		//小视屏
		document.getElementById("takeVideo").addEventListener('tap', function() {
			console.log('takevideo');
			getVideo();
		});
		document.getElementById("myfavorites").addEventListener('tap', function() {
			console.log('myfavorites');
		});
		document.getElementById("mylocal").addEventListener('tap', function() {
			console.log('mylocal');
			location.href = 'map.html';
		});
		document.getElementById("tovideonet").addEventListener('tap', function() {
			console.log('tovideonet');
		});
		document.getElementById("totags").addEventListener('tap', function() {
			console.log('totags');
		});
		document.getElementById("tofiles").addEventListener('tap', function() {
			location.href = 'file.html';
		});
		document.getElementById("tolangtrans").addEventListener('tap', function() {
			console.log('tolangtrans');
		});
		// 百度地图API功能
		/*
		var map = new BMap.Map("allmap");
		var point = new BMap.Point(116.331398, 39.897445);
		map.centerAndZoom(point, 12);
		map.disableDragging();
		// 创建地址解析器实例
		var myGeo = new BMap.Geocoder();

		// 将地址解析结果显示在地图上,并调整地图视野
		myGeo.getPoint("湖南省长沙市天心区芙蓉中路三段418号（芙蓉中路神龙大酒店对面）", function(point) {
			if(point) {
				map.centerAndZoom(point, 16);
				map.addOverlay(new BMap.Marker(point));
			} else {
				alert("您选择地址没有解析到结果!");
			}
		}, "北京市");*/

		connect();
	});
	//$.plusReady(function(){});

}(mui, document));